<!doctype html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../../css/mui.css" rel="stylesheet" />
		<style>
			.red-point{
	          position: relative;
	        }
	
	        .red-point::before{
	          content: " ";
	          border: 5px solid #C9394A;/*设置红色*/
	          border-radius:5px;/*设置圆角*/
	          position: absolute;
	          z-index: 3000;
	          right: 0%;
	          margin-right: -10px;
	          margin-top: 0px;
	        }
		</style>
	</head>

	<body>
		
		<div class="mui-content">
		    <ul class="mui-table-view" id="ul_friend_request_list" style="margin-bottom: 10px;">
				
			</ul>
			
			<ul id="ul_chatSnapshot" class="mui-table-view">
			</ul>
		</div>
		
		
		<script src="../../js/mui.min.js"></script>
		<script type="text/javascript" src="../../js/app.js" ></script>
		<script type="text/javascript">
			mui.init()
			mui.plusReady(function() {
				var user = app.getUserGlobalInfo();
				
				//加载好友请求记录
				var thisWebview = plus.webview.currentWebview();
				thisWebview.addEventListener("show", function() {
					getFriendsRequests();
				});
				
				CHAT.init();
				
				
				// 为好友通讯录批量绑定点击事件
				mui("#ul_chatSnapshot").on("tap", ".chat-with-friend", function(e){
					var friendUserId = this.getAttribute("friendUserId");
					var friendNickname = this.getAttribute("friendNickname");
					var friendFaceImage = this.getAttribute("friendFaceImage");
					
					// 打开聊天子页面
					mui.openWindow({
						url: "../chatList/chatting.html",
						id: "chatting-" + friendUserId + '.html',	// 每个朋友的聊天页面都是唯一对应的
						extras: {
							friendUserId: friendUserId,
							friendNickname: friendNickname,
							friendFaceImage: friendFaceImage
						}
					});
					
					//标记未读状态为已读
					app.readUserChatSnapshot(user.id, friendUserId);
					//渲染快照列表
					loadingChatSnapshot();
					
				})
			});
			
			window.CHAT = {
				socket: null,
				init: function() {
					if (window.WebSocket) {
						//判断当前是否已连接，无需重复初始化
						if (CHAT.socket != null && CHAT.socket != undefined && CHAT.socket.readyState == WebSocket.OPEN) {
							return true;
						}
						
						CHAT.socket = new WebSocket(app.wsUrl);
						CHAT.socket.onopen = CHAT.wsopen,
						CHAT.socket.onclose = CHAT.wsclose,
						CHAT.socket.onerror = CHAT.wserror,
						CHAT.socket.onmessage = CHAT.wsmsg;
					} else {
						alert("手机不支持");
					}
				},
				chat: function(msg) {
					console.log(msg);
					//判断当前是否已连接，无需重复初始化
					if (CHAT.socket != null && CHAT.socket != undefined && CHAT.socket.readyState == WebSocket.OPEN) {
						CHAT.socket.send(msg);
					} else {
						CHAT.init();
						setTimeout("CHAT.reChat('" + msg + "')","2000");
					}
					
					//渲染快照列表
					loadingChatSnapshot();
					
				},
				reChat: function(msg) {
					console.log("重新发送消息");
					CHAT.socket.send(msg);
				},
				wsopen: function() {
					console.log("连接建立成功");
					
					var me = app.getUserGlobalInfo();
					var chatMsg = new app.ChatMsg(me.id, null, null, null);
					var dataContent = new app.DataContent(app.CONNECT, chatMsg, null);
					CHAT.chat(JSON.stringify(dataContent));
					
					//每次重新链接后获取未签收列表
					fetchUnreadMsgList();
				},
				wsclose: function() {
					console.log("连接关闭...");
				},
				wserror: function(e) {
					console.log(e);
					console.log("发生错误...");
				},
				wsmsg: function(e) {
					console.log("接受到消息：" + e.data);
					var dataContent = JSON.parse(e.data);
					var action = dataContent.action;
					if (action === app.PULL_FRIEND) {
						plus.webview.getWebviewById("contact.html").reload(true);
						return true;
					}
					
					var chatMsg = dataContent.chatMsg;
					var msg = chatMsg.msg;
					var friendUserId = chatMsg.senderId;
					
					var chattingWebview = plus.webview.getWebviewById("chatting-" + friendUserId +".html");
					//设置消息默认状态为已读
					var isRead = true;
					if (chattingWebview != null) {
						chattingWebview.evalJS("receiveMsg('" + msg + "')");
					} else {
						isRead = false;  //聊天页面没有打开，未读消息
					}
					
					//签收消息
					var dataContentSign = new app.DataContent(app.SIGNED, null, chatMsg.msgId);
					CHAT.chat(JSON.stringify(dataContentSign));
					
					//保存接收到的消息到本地缓存
					app.saveUserChatHistory(chatMsg.receiverId, chatMsg.senderId, msg, 2);
					//保存接收到的消息到快照
					app.saveUserSnapshot(chatMsg.receiverId, chatMsg.senderId, msg, isRead);
					//渲染快照列表
					loadingChatSnapshot();
					
				},
				/**
				 * 批量签收
				 * @param {Object} unsignedMsgId
				 */
				signMsgList: function(unsignedMsgId) {
					//构建批量签收对象模型
					var dataMsgContent = new app.DataContent(app.SIGNED, null, unsignedMsgId);
					CHAT.chat(JSON.stringify(dataMsgContent));
				}
			};
			
			
			function getFriendsRequests() {
				var user = app.getUserGlobalInfo();
				mui.ajax(app.serverUrl + "/u/queryFriendRequests?userId=" + user.id,{
					data:{},
					dataType:'json',//服务器返回json格式数据
					type:'post',//HTTP请求类型
					timeout:10000,//超时时间设置为10秒；
					headers:{'Content-Type':'application/json'},	              
					success:function(data){
						if(data.status == 200) {
							var friendReuqestList = data.data;
							var ul_friend_request_list = document.getElementById("ul_friend_request_list");
							var requestHtml = "";
							if(friendReuqestList != null && friendReuqestList.length > 0) {
								for (var i = 0; i < friendReuqestList.length; i++) {
									requestHtml += renderFriendRequests(friendReuqestList[i]);
								}
							}
							ul_friend_request_list.innerHTML = requestHtml;
							
							//忽略
							mui(".btnOper").on("tap",".ignoreRequest", function(e) {
								var friendId = this.getAttribute("friendId");
								operatorFriendRequest(user.id, friendId, 0);
							});
							//同意
							mui(".btnOper").on("tap",".passRequest", function(e) {
								var friendId = this.getAttribute("friendId");
								operatorFriendRequest(user.id, friendId, 1);
							});
						} else {
							
						}
					},
					error: function(e) {
						console.log(JSON.stringify(e));
					}
				});
			}
			
			
			// 操作好友请求
			function operatorFriendRequest(userId, friendId, operType) {
				console.log(userId);
				console.log(friendId);
				console.log(operType);
				mui.ajax(app.serverUrl + "/u/operFriendRequest?acceptUserId=" + userId
												+ "&sendUserId=" + friendId
												+ "&operType=" + operType,{
					data:{},
					dataType:'json',//服务器返回json格式数据
					type:'post',//HTTP请求类型
					timeout:10000,//超时时间设置为10秒；
					headers:{'Content-Type':'application/json'},	              
					success:function(data){
						var myFriends = data.data;
						app.setContactList(myFriends);
						//刷新好友请求记录
						getFriendsRequests();
					}
				});
			}
			
			//拼接好友请求
			function renderFriendRequests(friend) {
				var html = "";
				
				html = '<li class="btnOper mui-table-view-cell mui-media">' +
					        '<a href="javascript:;">' +
					            '<img class="mui-media-object mui-pull-left" src="' + app.fileUrl + friend.sendFaceImage + '">' +
					            '<span id="span_nickname" class="mui-pull-right">' +
					            	'<button friendId="' + friend.sendUserId + '" type="button" class="ignoreRequest mui-btn mui-btn-grey" style="padding: 4px 10px;margin-right:5px;">忽略</button>' +
					            	'<button friendId="' + friend.sendUserId + '" type="button" class="passRequest mui-btn mui-btn-danger" style="padding: 4px 10px;">通过</button>' +
					            '</span>' +
					            '<div class="mui-media-body">' +
					               '<label>' + friend.sendNickname + '</label>' +
					                '<p class="mui-ellipsis">请求添加你为朋友</p>' +
					            '</div>' +
					        '</a>' +
						'</li>';
				
				return html;
			}
			
			//渲染聊天快照
			function loadingChatSnapshot() {
				console.log("aaaaaaaaa");
				var user = app.getUserGlobalInfo();
				var chatSnapshotList = app.getUserChatSnapshot(user.id);
				
				var chatSnapShotHtml = "";
				var ul_chatSnapshot = document.getElementById("ul_chatSnapshot");
				ul_chatSnapshot.innerHTML = "";
				for (var i = 0;i < chatSnapshotList.length; i++) {
					var chatItem = chatSnapshotList[i];
					var friendId = chatItem.friendId;
					//根据friendId从本地联系人缓存种获取响应信息
					var friend = app.getFriendFromContactList(friendId);
					
					var isRead = chatItem.isRead;
					var readHtmlBefore = '';
					var readHtmlAfter = '';
					if (isRead == false) {
						readHtmlBefore = '<span class="red-point">';
						readHtmlAfter = '</span>';
					}
					if (friend != null) {
//						console.log("222");
						chatSnapShotHtml = '<li friendUserId="' + friend.friendUserId + '" friendNickname="' + friend.friendNickname + '" friendFaceImage="' + friend.friendFaceImage + '"  class="chat-with-friend mui-table-view-cell mui-media">' +
										'<div class="mui-slider-right mui-disabled">' +
											'<a id="link_delChatRecord" friendUserId="' + friendId + '" class="mui-btn mui-btn-red">删除</a>' +
										'</div>' +
										'<div class="mui-slider-handle mui-media-body ">' +
								            '<img class="mui-media-object mui-pull-left" src="' + app.fileUrl + friend.friendFaceImage + '"/>' +
								            readHtmlBefore + friend.friendNickname + readHtmlAfter + 
								            '<p class="mui-ellipsis">' + chatItem.msg + '</p>' +
							            '</div>' +
								    '</li>';
						ul_chatSnapshot.insertAdjacentHTML("beforeend", chatSnapShotHtml);
					}
					
				}
			}
			
			/**
			 * 每次重连后获取服务器的未签收消息
			 */
			function fetchUnreadMsgList() {
				var user = app.getUserGlobalInfo();
				var msgIds = ","; //格式,1001,1002,1003,
				mui.ajax(app.serverUrl + "/u/getUnreadMsgList?acceptUserId=" + user.id,{
					data:{},
					dataType:'json',//服务器返回json格式数据
					type:'post',//HTTP请求类型
					timeout:10000,//超时时间设置为10秒；
					headers:{'Content-Type':'application/json'},	              
					success:function(data){
						var unreadList = data.data;
						console.log(JSON.stringify(unreadList));
						
						//保存聊天记录
						//保存聊天快照
						//批量签收
						for (var i=0;i < unreadList.length;i++) {
							var msgObj = unreadList[i];
							//保存聊天记录
							app.saveUserChatHistory(msgObj.acceptUserId, msgObj.sendUserId, msgObj.msg, 2);
							//保存聊天快照
							app.saveUserSnapshot(msgObj.acceptUserId, msgObj.sendUserId, msgObj.msg, false);
							//拼接批量签收的消息id
							msgIds += msgObj.id;
							msgIds += ",";
						}
						
						//批量签收
						CHAT.signMsgList(msgIds);
						//刷新快照
						loadingChatSnapshot();
					}
				});
			}
		
		
		</script>
	</body>

</html>